package com.fau.hm.action.index;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.fau.hm.action.PublicAction;
import com.fau.hm.entity.MedicalAdmin;
import com.fau.hm.entity.MedicalResource;
import com.fau.hm.util.DateUtil;
import com.fau.hm.util.FileNameEncoderUtil;
import com.opensymphony.xwork2.ModelDriven;

@Controller
@Scope("prototype")
@ParentPackage("default")
@Namespace("/")
public class UserAction extends PublicAction implements ModelDriven<MedicalAdmin> {

	private static final long serialVersionUID = -2061560598783331675L;

	private MedicalAdmin admin = new MedicalAdmin();
	
	@Value("${server.local.name}")
	private String urlPath;
	
	@Action(value = "login", results = {@Result(name = SUCCESS, location = "login.jsp")})
	public String login(){
		return SUCCESS;
	}
	
	@Action(value = "index", results = {@Result(name = SUCCESS, location = "main.jsp")})
	public String index(){
		return SUCCESS;
	}
	
	@Action(value = "loadMenu")
	public String loadMenu() {
		HttpServletResponse response = ServletActionContext.getResponse();
		List<MedicalResource> list = baseAllService.getUserService().loadMenu();
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 初始化用户列表页
	 * @return String
	 * @author dangjh
	 * @datetime 2014年10月12日,下午2:34:48
	 */
	@Action(value = "init_user_list", results = {@Result(name = SUCCESS, location = "init_user_list.jsp")})
	public String initUserList(){
		return SUCCESS;
	}
	
	/**
	 * @desc 加载用户数据列表
	 * @return String
	 * @author dangjh
	 * @datetime 2014年10月12日,下午2:37:15
	 */
	@Action(value = "user_list_view")
	public String userListView(){
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		admin.setEnterpriseId(user.getEnterpriseId());
		map = ServletActionContext.getContext().getParameters();
		pageBean = this.baseAllService.getUserService().findAllUsers(map, admin);
		map.clear();
		map.put("total", pageBean.getTotalRow());
		map.put("data", pageBean.getResult());
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 实例用户添加界面
	 * @return String
	 * @author dangjh
	 * @datetime 2014年10月14日,下午3:39:25
	 */
	@Action(value = "medical_user_add", results = {@Result(name = SUCCESS, location = "medical_user_add.jsp")})
	public String userAdd(){
		return SUCCESS;
	}
	
	/**
	 * @desc 判断登录名称是否唯一
	 * @return String
	 * @author dangjh
	 * @datetime 2014年10月15日,下午5:27:36
	 */
	@Action(value = "verify_username_only")
	public String userNameOnly(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(admin.getUsername())){
			MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			Boolean flag = this.baseAllService.getUserService().findUserByUserName(user.getEnterpriseId(), admin.getUsername());
			if(flag){
				map.put("result", "false");
			}else{
				map.put("result", "true");
			}
		}else{
			map.put("result", "error");
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 保存添加的用户信息
	 * @return String
	 * @author dangjh
	 * @datetime 2014年10月14日,下午3:40:53
	 */
	@Action(value = "medical_user_save")
	public String userSave(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		map = new HashMap<String, Object>();
		MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		admin.setEnterpriseId(user.getEnterpriseId());
		if(StringUtils.isNotBlank(admin.getDeptType()) && StringUtils.isNotBlank(admin.getRoleId())){
			admin.setCreateIp(this.getIp(request));
			boolean flag = this.baseAllService.getUserService().save(admin);
			if(flag){
				map.put("success", true);
			}else{
				map.put("success", false);
			}
		} else {
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 实例用户编辑界面
	 * @return String
	 * @author dangjh
	 * @datetime 2014年10月14日,下午3:42:58
	 */
	@Action(value = "medical_user_edit", results = {@Result(name = SUCCESS, location = "medical_user_edit.jsp")})
	public String userEdit(){
		return SUCCESS;
	}
	
	/**
	 * @desc 保存修改的用户信息
	 * @return String
	 * @author dangjh
	 * @datetime 2014年10月14日,下午3:48:14
	 */
	@Action(value = "medical_useredit_save")
	public String userEditSave(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(admin.getId())){
			boolean flag = this.baseAllService.getUserService().saveEdit(admin);
			if(flag){
				map.put("success", true);
			}else{
				map.put("success", false);
			}
		}else{
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 获取用户组
	 * @return null
	 * @author dangjh
	 * @datetime 2014年10月14日,下午8:06:12
	 */
	@Action(value = "user_group_view")
	public String userGroupView(){
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		list = this.baseAllService.getUserService().findGroupByEid(user);
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 获取用户角色信息
	 * @return null
	 * @author dangjh
	 * @datetime 2014年10月16日,下午5:22:56
	 */
	@Action(value = "user_role_view")
	public String userRoleView(){
		HttpServletResponse response = ServletActionContext.getResponse();
		MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		list = this.baseAllService.getUserService().findRoleByEid(user);
		formatJSON(response, list);
		return null;
	}
	
	/**
	 * @desc 删除用户信息
	 * @return null
	 * @author dangjh
	 * @datetime 2014年10月16日,下午10:36:03
	 */
	@Action(value = "meidcal_user_del")
	public String userDel(){
		HttpServletResponse response = ServletActionContext.getResponse();
		map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(admin.getId())){
			this.baseAllService.getUserService().delUser(admin);
			map.put("success", true);
		}else{
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 导出当前页面数据
	 * @return null
	 * @author dangjh
	 * @datetime 2014年10月20日,上午11:51:07
	 */
	@Action(value = "export_current_data")
	public String exportCurrent(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		String ids = request.getParameter("ids");
		try {
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"员工信息管理"+DateUtil.getDate()+".xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			Workbook workbook = this.baseAllService.getUserService().currentPage(ids);
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @desc 导出所有员工信息
	 * @return
	 * @author dangjh
	 * @datetime 2014年10月20日,上午11:51:49
	 */
	@Action(value = "export_all_data")
	public String exportAll(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"员工信息管理"+DateUtil.getDate()+".xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			Workbook workbook = this.baseAllService.getUserService().allPage(user);
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * @desc 打开批量导入页面
	 * @return
	 * @author kangyj
	 * @datetime 2014年10月15日,下午10:19:19
	 */
	@Action(value = "medical_user_import_add", results = {@Result(location = "medical_user_import_add.jsp")})
	public String importAdd(){
		return SUCCESS;
	}
	
	/**
	 * @desc 导入保存
	 * @return
	 * @author kangyj
	 * @datetime 2014年10月22日,上午9:53:43
	 */
	@Action(value = "medical_user_import_save")
	public String importSave(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		map = new HashMap<String, Object>();
		MedicalAdmin admin = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		File file = this.getImportFile(request, response);
		try {
			admin.setCreateIp(this.getIp(request));
			this.baseAllService.getUserService().importSave(admin, file);
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
		}
		formatJSON(response, map);
		return null;
	}
	
	/**
	 * @desc 下载员工信息模板
	 * @return
	 * @author dangjh
	 * @datetime 2014年11月7日,下午2:32:08
	 */
	@Action(value = "download_user_template")
	public String downloadTemplate(){
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			MedicalAdmin user = (MedicalAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			response.addHeader("Content-Disposition", "attachment;filename=" + FileNameEncoderUtil.encode(request,"员工信息模板"+DateUtil.getDate()+".xls"));
			response.setContentType("application/vnd.ms-excel");
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			Workbook workbook = this.baseAllService.getUserService().template(user);
			workbook.write(toClient);
			toClient.flush();
			toClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	@Override
	public MedicalAdmin getModel() {
		return admin;
	}
	
	public String getUrlPath() {
		return urlPath;
	}

	public void setUrlPath(String urlPath) {
		this.urlPath = urlPath;
	}

}
